const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/region')
//省
const provinceSchema = new mongoose.Schema({
    name: String,
});
const Province = mongoose.model('Province', provinceSchema);


//市
const citySchema = new mongoose.Schema({
    name: String,
    province: { type: mongoose.SchemaTypes.ObjectId, ref: 'Province' } // 引用省份的ID
});
const City = mongoose.model('City', citySchema);


//区
const districtSchema = new mongoose.Schema({
    name: String,
    city: { type: mongoose.SchemaTypes.ObjectId, ref: 'City' } // 引用城市的ID
});
const District = mongoose.model('District', districtSchema);


// 首先插入省份数据，并获取ID用于后续引用
// const china = new Province({ name: '中国' });
// china.save().then(a=>{
//     console.log('ss',a);
// })
// china.save().then(province => {
//   const beijing = new City({ name: '北京市', province: province._id }); // 使用_id引用省份ID
//   beijing.save().then(city => {
//     new District({ name: '东城区', city: city._id }).save(); // 使用_id引用城市ID
//     new District({ name: '西城区', city: city._id }).save(); // 使用_id引用城市ID（同一城市）
//   });
// });
//把所有异步操作，比如操作数据库，读取数据库都放在async await中，好控制一些
async function main() {
    await Province.insertOne({ name: '中国1' });
    await City.insertMany([
        { name: '北京市1'}
    ])
    await District.insertMany([
        { name: '东城区1'},
        { name: '西城区1'}
    ])
    const p1 = await Province.findOne({ name: '中国1' })
    const c1 = await City.findOne({name:'北京市1'})
    const d1 = await District.findOne({name:'东城区1'})
    const d2 = await District.findOne({name:'西城区1'})
    c1.province = p1;
    d1.city = c1;
    d2.city = c1;
    await c1.save();
    await d1.save();
    await d2.save();
    const provinces = await Province.find().populate('province')
    await console.log('yuu', provinces);
}
main()
